package com.net.xpay.openapi.service.impl;


import com.alipay.api.AlipayApiException;
import com.google.common.base.Strings;
import com.net.common.exception.BusinessException;
import com.net.xpay.alipay.PoseidonAlipayClient;
import com.net.xpay.common.domain.User;
import com.net.xpay.common.helper.RedisHelper;
import com.net.xpay.common.manager.UserManager;
import com.net.xpay.core.constant.PoseidonErrorCode;
import com.net.xpay.core.constant.RedisKey;
import com.net.xpay.core.domain.AlipayUser;
import com.net.xpay.core.enums.AlipayUserStatus;
import com.net.xpay.core.manager.AlipayUserManager;
import com.net.xpay.core.model.AlipayUserSearchModel;
import com.net.xpay.openapi.model.OpenApiAlipayAuthAuthPageGoModel;
import com.net.xpay.openapi.service.OpenApiAlipayAuthService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 开放平台批量有密签约管理
 */
@Slf4j
@Service
public class OpenApiAlipayAuthServiceImpl implements OpenApiAlipayAuthService {

    @Autowired
    private UserManager userManager;

    @Autowired
    private AlipayUserManager alipayUserManager;

    @Autowired
    private PoseidonAlipayClient xpayAlipayClient;

    @Autowired
    private RedisHelper redisHelper;


    @Override
    public String doAlipayAuth(OpenApiAlipayAuthAuthPageGoModel authModel, User user) {
        if (Strings.isNullOrEmpty(authModel.getAlipayNickName())) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "请输入支付宝账号");
        }
        if (Strings.isNullOrEmpty(authModel.getReturnUrl())) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "签约完成回跳地址不能为空");
        }

        String alipayNickName = authModel.getAlipayNickName();
        Long userId = user.getId();
        //先从缓存中查，如果没有再请求新的
        Object authUrl = redisHelper.get(RedisKey.AUTH_ALIPAY_USER_URL + ":" + user.getId() + ":" + alipayNickName + ":" + authModel.getReturnUrl());
        if (authUrl != null) {
            AlipayUser alipayUser = alipayUserManager.findByAlipayNickName(user.getId(), alipayNickName);
            if (alipayUser != null) {
                alipayUser.setIsDeleted(0);
                alipayUserManager.updateByPrimaryKeyWithVersion(alipayUser);
            }
            return authUrl.toString();
        }

        String isvBizId = userId + "-" + System.currentTimeMillis();
        String authPageUrl;
        try {
            authPageUrl = xpayAlipayClient.alipayOpenInviteOrderCreate(isvBizId, authModel.getAlipayNickName(), authModel.getReturnUrl());
        } catch (AlipayApiException e) {
            log.info("doAlipayAuth error", e);
            throw new BusinessException(PoseidonErrorCode.UNKNOWN_ERROR, "系统异常");
        }

        AlipayUser alipayUser = alipayUserManager.findByAlipayNickName(userId, alipayNickName);
        if (alipayUser == null) {
            alipayUser = AlipayUser.getInstance();
            alipayUser.setUserId(userId);
            alipayUser.setMobile(user.getMobile());
            alipayUser.setAlipayNickName(alipayNickName);
            // 异步消息需要根据isvBizId来获取对应token
            alipayUser.setIsvBizId(isvBizId);
            alipayUser.setStatus(AlipayUserStatus.NO);
            alipayUser.setIsDeleted(0);
            alipayUserManager.save(alipayUser);

            //将第一个绑定的号作为主支付宝账号
            AlipayUserSearchModel searchModel = new AlipayUserSearchModel();
            searchModel.setUserId(user.getId());
            long count = alipayUserManager.searchCount(searchModel);
            if (count == 1L) {
                User selectedUser = userManager.getById(user.getId());
                selectedUser.setAlipayNickName(alipayNickName);
                selectedUser.setAlipayUserId(alipayUser.getId());
                userManager.updateByPrimaryKeyWithVersion(selectedUser);
            }
        } else {
            alipayUser.setStatus(AlipayUserStatus.NO);
            alipayUser.setIsvBizId(isvBizId);
            alipayUser.setIsDeleted(0);
            alipayUserManager.updateByPrimaryKeyWithVersion(alipayUser);
        }

        redisHelper.set(RedisKey.AUTH_ALIPAY_USER_URL + ":" + user.getId() + ":" + alipayNickName + ":" + authModel.getReturnUrl(), authPageUrl, 60 * 30L);
        return authPageUrl;
    }
}
